package com.my.pojo;

import com.my.util.CryptoUtil;
import com.my.util.RSACoder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 钱包
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Wallet {
  /**
   * 公钥
   */
  private String publicKey;
  /**
   * 私钥
   */
  private String privateKey;

  /**
   * 只包含公钥的钱包,用来给其他节点使用,其他节点在转账时用到
   * @param publicKey
   */
  public Wallet(String publicKey){
    this.publicKey = publicKey;
  }

  public static Wallet generateWallet(){
    Map<String,Object> initKey;
    try {
      //本地生成公私钥对
      initKey = RSACoder.initKey();
      String publicKey = RSACoder.getPublicKey(initKey);
      String privateKey = RSACoder.getPrivateKey(initKey);
      return new Wallet(publicKey,privateKey);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 获取钱包地址
   * @return
   */
  public String getAddress(){
    String publicKeyHash= hashPubKey(publicKey);
    return CryptoUtil.MD5(publicKeyHash);
  }

  /**
   * 生成钱包公钥hash
   * @param
   * @return
   */
  public String getHashPubKey() {

    return CryptoUtil.SHA256(publicKey);
  }

  /**
   * 生成钱包公钥hash
   * @param publicKey
   * @return
   */
  public static String hashPubKey(String publicKey) {

    return CryptoUtil.SHA256(publicKey);
  }


}
